﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using IBatisNet.DataMapper.Configuration;
using IBatisNet.DataMapper;

namespace ConsoleApp.MyBatis
{
    public static class demo_mybatis
    {
        public static void demo()
        {
            IApplicationContext ctx = ContextRegistry.GetContext();

            DomSqlMapBuilder sqlMapperBuilder = ctx.GetObject("builder") as DomSqlMapBuilder;
            ISqlMapper sqlMapper = ctx.GetObject("sqlMapper") as ISqlMapper;
            ProductRepository productRepository = ctx.GetObject("ProductRepository") as ProductRepository;

            //ISqlMapSession sqlSession = sqlMapper.BeginTransaction();
            sqlMapper.BeginTransaction();
            int insertProductId = 0;
            try
            {
                //插入
                var product = new ProductEntity()
                {
                    ProductCompany = "INFOSKY",
                    ProductName = "iGSA2",
                    SignDate = DateTime.Now,
                    UpdateDate = DateTime.Now
                };

                insertProductId = productRepository.Insert<ProductEntity>("InsertProduct", product);

                //查单条记录
                var model = productRepository.Get<ProductEntity>("SelectByProductId", insertProductId);

                //修改记录
                if (model != null)
                {
                    model.ProductName = (new Random().Next(0, 99999999)).ToString().PadLeft(10, '0');
                    int updateResult = productRepository.Update<ProductEntity>("UpdateProduct", model);
                    Console.WriteLine("update影响行数:" + updateResult + "<br/><hr/>");
                }

                //sqlSession.CommitTransaction(false);
                sqlMapper.CommitTransaction(true);
            }
            catch 
            {
                //sqlSession.RollBackTransaction(false);
                sqlMapper.RollBackTransaction(true);
            }

            //查列表
            var products = productRepository.QueryForList<ProductEntity>("SelectAllProduct");

            foreach (var pro in products)
            {
                ShowProduct(pro);
            }

            //删除记录
            int deleteResult = productRepository.Delete("DeleteProductById", insertProductId);
            Console.WriteLine("delete影响行数:" + deleteResult + "<br/><hr/>");
        }


        static void ShowProduct(ProductEntity pro)
        {
            if (pro == null) return;
            Console.WriteLine(pro.ToString());
        }
    }
}
